/*
 * File Name：MainActivity.java
 * Copyright：Copyright 2008-2014 CiWong.Inc. All Rights Reserved.
 * Description： MainActivity.java
 * Modify By：bin
 * Modify Date：2014年4月7日
 * Modify Type：Add
 */
package com.ciwong.mobilepay.ui;

import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.support.v4.content.res.ResourcesCompat;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.DeviceUtils;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.libs.utils.StringUtils;
import com.ciwong.libs.utils.volley.HttpRequest;
import com.ciwong.mobilelib.R;
import com.ciwong.mobilelib.application.BaseApplication;
import com.ciwong.mobilelib.widget.CWDialog;
import com.ciwong.mobilelib.widget.NewCWProgressBar;
import com.ciwong.mobilepay.adapter.PayMethodAdapter;
import com.ciwong.mobilepay.alipay.AlipayHelper;
import com.ciwong.mobilepay.alipay.AlipayListener;
import com.ciwong.mobilepay.bean.OrderInfo;
import com.ciwong.mobilepay.bean.PayDetail;
import com.ciwong.mobilepay.bean.PayMethod;
import com.ciwong.mobilepay.bean.PayResult;
import com.ciwong.mobilepay.bean.Recharge;
import com.ciwong.mobilepay.bean.SignParms;
import com.ciwong.mobilepay.bean.SignResult;
import com.ciwong.mobilepay.bean.UnionPayResult;
import com.ciwong.mobilepay.bean.VirtualBalance;
import com.ciwong.mobilepay.util.MPAction;
import com.ciwong.mobilepay.util.MPConstants;
import com.ciwong.mobilepay.util.PayUtil;
import com.ciwong.mobilepay.util.RC4;
import com.ciwong.mobilepay.view.EPayMain;
import com.ciwong.mobilepay.view.EPayMethodContainer;
import com.ciwong.mobilepay.view.PayDetailContainer;
import com.ciwong.mobilepay.view.PayMain;
import com.ciwong.mobilepay.weixin.WxPayHelper;
import com.ciwong.mobilepay.weixin.WxPayListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 移动支付主Activity
 *
 * @author bin
 * @version ciwong v.1.0 2014年4月7日
 * @since ciwong v.1.0
 */
public class EMainActivity extends MPBaseActivity implements
        android.view.View.OnClickListener {
    /**
     * 广告activity的所在包名及activity
     */
    public static final String ADV_PKG_NAME = "ADV_PKG_NAME";

    public static final String PAY_DETAIL = "PAY_DETAIL";

    public static final String PAY_RESULT = "pay_result";

    public static final int REQUEST_CODE = 10000;

    public static final int REQUEST_CODE_QRCODE_PAY = 10001;

    /**
     * 支付结果:成功
     */
    public static final int PAY_RESULT_SUCCES = 0;

    /**
     * 支付结果:失败
     */
    public static final int PAY_RESULT_FAIL = 1;

    /**
     * 支付结果:延时
     */
    public static final int PAY_RESULT_DELAY = 2;

    /**
     * "00" - 启动银联正式环境 "01" - 连接银联测试环境
     */
    private static final String MODE = "00";

    private PayDetail mPayDetail;

    private String advPkgName;

    private ViewGroup container, payMethodVirtualContainer;

    private ImageView payDetailIcon;

    private TextView payDetailName, payDetailPrice, payDetailNumber,
            payDetailTotal;

    /**
     * 可用习币单选框
     */
    private CheckBox payMethodVirtual;

    private ImageView ivPayMethodVirtual;

    private TextView tvPayMethodVirtual;

    private TextView payMethodLack;

    private ListView payMethodLV;

    private PayMethodAdapter pmAdapter;

    private TextView payMethodPassword;

    private EditText payMethodPasswordET;

    private Button payOK;

    private CWDialog payDialog;

    /**
     * 订单信息
     */
    private OrderInfo order;

    /**
     * 下单时间
     */
    private String orderTime;

    /**
     * 合计
     */
    private double total;

    /**
     * 用户帐号余额信息
     */
    private VirtualBalance vb;

    /**
     * 客户端支付是否成功
     */
    private boolean success;

    private ImageView progressBar;

    private ViewGroup balanceContainer, payPasswordContainer;

    private NewCWProgressBar cProgressBar;

    private DisplayImageOptions faceOption;

    private boolean isPayFailure, isUnionPay;

    /**
     * 获取订单状态次数
     */
    private int count;

    private Handler mHandler = new Handler();

    /**
     * 微信支付回调
     */
    private WxPayListener listener = new WxPayListener() {

        @Override
        public void onWXPaying(String msg) {

        }

        @Override
        public void onWXPaySucc(String resultInfo) {
            CWLog.d("PayRequest", "onWXPaySucc:结果:" + resultInfo);
            success = true;
            getRechargeInfo(mPayDetail.getUserId(), order.getRechargeNo());
        }

        @Override
        public void onWXPayFailure(int errCode, String errMsg) {
            success = false;
            CWLog.d("debug", "#####onWXPayFailure###");
            showError(errMsg);
        }

        @Override
        public void onWXPayCencel() {
            success = false;
            showError("您取消了支付");
        }
    };

    @Override
    public void preCreate() {
        mPayDetail = (PayDetail) getIntent().getSerializableExtra(PAY_DETAIL);
        advPkgName = getIntent().getStringExtra(ADV_PKG_NAME);
        DeviceUtils.setContext(this);
        NetworkUtils.setContext(this);
    }

    @Override
    protected View setView() {
        return new EPayMain(this, mPayDetail.getTypeId() == 5 ? 2 : 3);
    }

    private void showProgress(String str) {
        if (cProgressBar == null) {
            cProgressBar = new NewCWProgressBar(this);
            cProgressBar.setCanceledOnTouchOutside(false);
        }
        cProgressBar.setMessage(str);
        cProgressBar.show();
    }

    private void hideProgress() {
        if (cProgressBar != null & !isFinishing() && cProgressBar.isShowing()) {
            cProgressBar.dismiss();
        }
    }

    @Override
    protected void findViews() {
        container = (ViewGroup) findViewById(PayMain.container);
        payDetailIcon = (ImageView) findViewById(PayDetailContainer.payDetailIcon);
        payDetailName = (TextView) findViewById(PayDetailContainer.payDetailName);
        payDetailPrice = (TextView) findViewById(PayDetailContainer.payDetailPrice);
        payDetailNumber = (TextView) findViewById(PayDetailContainer.payDetailNumber);
        payDetailTotal = (TextView) findViewById(PayDetailContainer.payDetailTotal);

        payMethodVirtualContainer = (ViewGroup) findViewById(EPayMethodContainer.payMethodVirtualContainer);
        payMethodVirtual = (CheckBox) findViewById(EPayMethodContainer.payMethodVirtual);
        ivPayMethodVirtual = (ImageView) findViewById(EPayMethodContainer.payMethodVirtualIv);
        payMethodLack = (TextView) findViewById(EPayMethodContainer.payMethodLack);
        payMethodLV = (ListView) findViewById(EPayMethodContainer.payMethodLV);
        payMethodPassword = (TextView) findViewById(EPayMethodContainer.payMethodPassword);
        payMethodPasswordET = (EditText) findViewById(EPayMethodContainer.payMethodPasswordET);
        payOK = (Button) findViewById(EPayMain.payOk);
        progressBar = (ImageView) findViewById(EPayMethodContainer.loading);
        balanceContainer = (ViewGroup) findViewById(EPayMethodContainer.balanceContainer);
        payPasswordContainer = (ViewGroup) findViewById(EPayMethodContainer.payPasswordContainer);
        tvPayMethodVirtual = (TextView) findViewById(EPayMethodContainer.payMethodVirtualTv);
    }

    @Override
    protected void initEvent() {
        Intent mIntent = getIntent();
        Object obj = mIntent.getSerializableExtra(PAY_DETAIL);
        // if (obj != null)
        // {
        HttpRequest.registAction(this.getClass().getName(), new MPAction());
        mPayDetail = (PayDetail) obj;
        // }
        if (mPayDetail == null) {
            mPayDetail = new PayDetail();
            mPayDetail
                    .setIcon("http://img1.ciwong.net/uidimg_default/333975356/100?oldrand=635278186634375726");
            mPayDetail.setName("iPhone 5s");
            mPayDetail.setPrice(0.01f);
            mPayDetail.setNumber(1);
            mPayDetail.setUserId(12121);
            mPayDetail.setName("yang");
            mPayDetail.setBuyType(1);
            StringBuilder sb = new StringBuilder(
                    "http://192.168.120.219:8080/appsystem/client/payApp?payPassword=%s");
            sb.append("&appId=1967");
            sb.append("&userId=333975353");
            sb.append("&charge=1");
            long timestamp = System.currentTimeMillis();
            sb.append("&timestamp=" + timestamp);
            sb.append("&auth="
                    + StringUtils
                    .md5("c10f72d56a3e097884ebc21a51a5b78e13339753531967"
                            + timestamp));
            mPayDetail.setNotifyUrl(sb.toString());
            HttpRequest.VerifyInfo verifyInfo = new HttpRequest.VerifyInfo();
            verifyInfo
                    .setAccessToken("9a3f57b728ef4f6dbc007d0c6580509f5b33bee0");
            verifyInfo.setClientId("100008");
            verifyInfo.setClientIp("192.168.90.18");
            verifyInfo.setOauthVersion("2.a");
            verifyInfo.setOpenId("70496c6e36a59d6be3ab9cdfc383feab");
            verifyInfo.setScope("all");
            mPayDetail.setVerifyInfo(verifyInfo);
            SignParms signparms = new SignParms();
            signparms.setBrandId(1);
            signparms.setGoods_num(1);
            signparms.setRechargeType("1");
            signparms.setServiceId("");
            signparms.setTotal_fee(12);
            signparms.setUserId(12121);
            signparms.setUserName("young");
            mPayDetail.setSingParms(signparms);
            HttpRequest.setVerifyInfo(mPayDetail.getVerifyInfo());

        }
        // mPayDetail.setNotifyUrl("http://121.14.117.225:8080/paytest/client/payTest");
        payMethodVirtual
                .setOnCheckedChangeListener(new OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(CompoundButton buttonView,
                                                 boolean isChecked) {
                        if (isChecked) {
                            if (total > vb.getAmount()) {
                                //余额不足  请及时充值   提示充值
                                payMethodLack.setVisibility(View.VISIBLE);
                            }
                            ivPayMethodVirtual.setSelected(true);
                        } else {
                            payMethodLack.setVisibility(View.GONE);
                            ivPayMethodVirtual.setSelected(false);

                        }

                        if (null != pmAdapter.getPayMethodBox()) {
                            pmAdapter.setChecked(pmAdapter.getPayMethodBox(), pmAdapter.getSelectPosition());
                        }
                    }
                });

        payMethodLV.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                ImageView payMethodBox = (ImageView) view
                        .findViewById(PayMethodAdapter.PayMethodItem.payMethodBoxIv);
                pmAdapter.setChecked(payMethodBox, position);

                if (null != ivPayMethodVirtual) {
                    ivPayMethodVirtual.setSelected(false);

                }
            }
        });

        payOK.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v)

            {
                SharedPreferences sp = getSharedPreferences("sp_time", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();

                long currentTimes = System.currentTimeMillis();
                long lastTimes = sp.getLong("time", 0);//配合服务器  为了不让重复购买   客户端限制点击购买按钮之后  10秒不让重复点击
                if (currentTimes - lastTimes > 10000) {//间隔时间大于10秒  则可以点击购买
                    payOK.setEnabled(true);
                    // createPayDialog();
                    if (!payMethodVirtual.isChecked()
                            && pmAdapter.getPayMethod().getPayType() == PayMethod.PayType.PAY_TYPE_DETAIL) {
                        showError("请选择支付方式");
                        return;
                    }
                    showProgress("正在支付");
                    // if (vb.isPaypwd())
                    // {
                    // passwordVerify();
                    // }
                    // else
                    // {

                    //开始支付    
                    pay();
                    editor.putLong("time", currentTimes);
                    editor.commit();
                } else if (currentTimes - lastTimes > 3000) {

                    Toast toast = Toast.makeText(EMainActivity.this, "操作过于频繁,请10秒后重试", Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                }
                //10秒不可点击
                // }
            }
        });
        // payDetailIcon
    }

    @Override
    protected void init() {
        setTitleBarText("支付详情");
        //不管支付什么这个ui都是显示名称
        payDetailName.setText(mPayDetail.getName());
        //购买服务的时候 标题栏显示价格
        if (1 == mPayDetail.getBuyType()) {
            payDetailPrice.setText(String.format("%s元",
                    PayUtil.radixPoint(mPayDetail.getPrice() - mPayDetail.getAmount(), 2)));
        } else if (2 == mPayDetail.getBuyType()) {//在线报名的时候
            payDetailPrice.setText(mPayDetail.getTitleRight());
        } else {//其他
            payDetailPrice.setText(mPayDetail.getTitleRight());
        }

        //购买服务的时候 详情页第二行的文字栏展示 
        if (1 == mPayDetail.getBuyType()) {
            payDetailNumber.setText(String.format("数量:%s", mPayDetail.getNumber()));
        } else if (2 == mPayDetail.getBuyType()) {//在线报名的时候
            payDetailNumber.setText(mPayDetail.getSecondText());//这个怎么显示 需要外面动态拼装
        } else {//其他
            payDetailNumber.setText(mPayDetail.getSecondText());
        }

        //合计
        total = mPayDetail.getPrice() * (float) mPayDetail.getNumber() - mPayDetail.getAmount();

        payDetailTotal.setText(Html.fromHtml(String.format("合计:%s",
                " <font color=\"#d50001\">￥" + PayUtil.radixPoint(total, 2)
                        + "</font>")));

        List<PayMethod> pms = new ArrayList<PayMethod>();
        PayMethod pm = new PayMethod();
        pm.setPayType(PayMethod.PayType.PAY_TYPE_WEI_XIN);
        pm.setName("微信");
        pm.setHint("推荐有微信账号用户使用");
        Drawable weixin_icon =
//                PayUtil.getDrawableFromJar(
//                "/images_mobilepay/weixin_icon.png", EMainActivity.class);
                ResourcesCompat.getDrawable(getResources(), R.mipmap.weixin_icon, null);

        pm.setIcon(weixin_icon);
        pms.add(pm);

        PayMethod pm2 = new PayMethod();
        pm2.setPayType(PayMethod.PayType.PAY_TYPE_ALIPAY);
        pm2.setName("支付宝");
        pm2.setHint("推荐有支付宝账号用户使用");
        Drawable alipay =
//                PayUtil.getDrawableFromJar(
//                "/images_mobilepay/alipay_icon.png", EMainActivity.class);

                ResourcesCompat.getDrawable(getResources(), R.mipmap.alipay_icon, null);
        pm2.setIcon(alipay);
        pms.add(pm2);
        pmAdapter = new PayMethodAdapter(this, pms);
        payMethodLV.setAdapter(pmAdapter);


//        payMethodLV.setSelection(0);


        //购买服务的显示  图标
        if (1 == mPayDetail.getBuyType()) {
            ImageLoader.getInstance().displayImage(mPayDetail.getIcon(),
                    payDetailIcon, getUserFaceOptions());
        } else if (2 == mPayDetail.getBuyType()) {//在线报名的时候 隐藏图片
            payDetailIcon.setVisibility(View.GONE);
        } else {//其他
            payDetailIcon.setVisibility(View.GONE);
        }


    }

    public DisplayImageOptions.Builder getDisplayBuilder() {
        Drawable cwIcon =
//                PayUtil.getDrawableFromJar(
//                "/images_mobilepay/cw_icon.png", EMainActivity.class);
                ResourcesCompat.getDrawable(getResources(), R.mipmap.cw_icon, null);
        return new DisplayImageOptions.Builder().cacheInMemory(true)
                .cacheOnDisc(true).showImageForEmptyUri(cwIcon)
                .showImageOnFail(cwIcon);
    }

    /**
     * 用户头像圆角大小
     */
    public static final int USER_FACE_ROUND = 20;

    /**
     * icon缓存目录
     */
    public static final String ICON_DIR = File.separator + "icon";

    /**
     * 获取圆角头像的option
     *
     * @return 用户头像
     */
    public DisplayImageOptions getUserFaceOptions() {
        if (faceOption == null) {
            Drawable cwIcon =
//                    PayUtil.getDrawableFromJar(
//                    "/images_mobilepay/cw_icon.png", EMainActivity.class);
                    ResourcesCompat.getDrawable(getResources(), R.mipmap.cw_icon, null);

            faceOption = getDisplayBuilder().showImageForEmptyUri(cwIcon)
                    .showImageOnFail(cwIcon).cacheInMemory(true)
                    .displayer(new RoundedBitmapDisplayer(USER_FACE_ROUND))
                    .build();
        }
        return faceOption;
    }

    @Override
    protected void loadData() {
        //开始加载网络 数据   请求账户余额
        getVirtualBalance(true);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        CWSys.hidKeyBoard();
        return super.onTouchEvent(event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data != null) {
                if (requestCode == REQUEST_CODE) {
                    setResult(RESULT_OK, data);
                    finish();
                } else {
                    String str = data.getStringExtra(PAY_RESULT);
                    if (str.equalsIgnoreCase("success")) {
                        success = true;
                        isUnionPay = true;
                        getRechargeInfo(mPayDetail.getUserId(),
                                order.getRechargeNo());
                        str = "支付成功！";
                    } else if (str.equalsIgnoreCase("fail")) {
                        success = false;
                        unionPayQuery();
                        str = "支付失败！";
                    } else if (str.equalsIgnoreCase("cancel")) {
                        success = false;
                        str = "用户取消了支付";
                        showError("您取消了支付");
                    }
                }
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        WxPayHelper.getInstance().onResumeResultData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        WxPayHelper.getInstance().release();
    }

    private void loadBalanceFailure() {
        balanceContainer.setVisibility(View.VISIBLE);
        tvPayMethodVirtual.setText("加载余额失败，点击重试");
        balanceContainer.setOnClickListener(this);
    }

    private void hideProgressBar() {
        progressBar.clearAnimation();
        progressBar.setVisibility(View.GONE);
    }

    /**
     * 获取习网用户支付信息
     * <p>
     * <p>
     * 查询 习币余额信息
     */
    private void getVirtualBalance(boolean showProgress) {
        if (showProgress) {
            progressBar.setVisibility(View.VISIBLE);
            balanceContainer.setVisibility(View.GONE);
            tvPayMethodVirtual.setText("");
        }
        Map<String, String> params = new HashMap<String, String>();
        params.put(HttpRequest.REQUEST_ACTION, MPAction.USER_BALANCE);
        params.put(HttpRequest.REQUEST_MODULES, getClass().getName());
        params.put("userId", mPayDetail.getUserId() + "");
        HttpRequest request = new HttpRequest(params,
                new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError arg0) {
                        vb = new VirtualBalance();
                        vb.setAmount(-1);
                        payOK.setEnabled(true);
                        loadBalanceFailure();
                        hideProgressBar();
                    }
                }, new HttpRequest.ResponseCallback() {

            @Override
            public void success(Object obj, int resultCode,
                                int errorCode, String msg) {
                if (resultCode == 0 && errorCode == 0) {
                    vb = (VirtualBalance) obj;

                    //在线报名   不支持习币购买
                    //当是在线报名的时  习币 余额为 0
                    if (2 == mPayDetail.getBuyType()) {
                        vb.setAmount(-1);
                    }


                    if (total <= vb.getAmount()) {
                        payMethodVirtualContainer
                                .setVisibility(View.VISIBLE);
                        tvPayMethodVirtual.setText(String.format(
                                "可用习币:  %s习币",
                                PayUtil.radixPoint(vb.getAmount(), 2)));
                        //此时有习币,习币为默认购买方式   隐藏默认微信支付


                    }
                    payOK.setEnabled(true);
                    payMethodVirtual.setEnabled(true);
                    balanceContainer.setVisibility(View.GONE);
                    if (isPayFailure && isUnionPay) {
                        if (vb.getAmount() > 0) {
                            payMethodVirtual.setChecked(true);
                        }
                        isPayFailure = false;
                        isUnionPay = false;
                    }
                    boolean checked = payMethodVirtual.isChecked();
                    if (checked) {
                        if (total > vb.getAmount()) {
                            payMethodLack.setVisibility(View.VISIBLE);
                        }
                    } else {
                        payMethodLack.setVisibility(View.GONE);
                    }
                } else {
                    loadBalanceFailure();
                }
                hideProgressBar();
            }

            @Override
            public void error(int errorCode, String msg) {
                vb = new VirtualBalance();
                vb.setAmount(-1);
                payOK.setEnabled(true);
                loadBalanceFailure();
                hideProgressBar();
            }
        });
        request.setResponseDataType(HttpRequest.RESPONSE_DATA_TYPE_OBJECT);
        request.setResponseClazz(VirtualBalance.class);
        Volley.newRequestQueue(getApplicationContext()).add(request);
    }

    /**
     * 查询支付成功后操作
     *
     * @param result 支付状态
     */
    private void payJump(int result) {
        Intent intent = getIntent();
        intent.setClass(EMainActivity.this, PayStatusActivity.class);
        intent.putExtra(PAY_RESULT, result);
        intent.putExtra(PAY_DETAIL, mPayDetail);
        intent.putExtra(ADV_PKG_NAME, advPkgName);
        startActivityForResult(intent, REQUEST_CODE);
    }


    /**
     * 老的习币支付
     */
    private void virtualPay(final int result) {
        // Map<String, String> params = new HashMap<String, String>();
        // String url = String.format(
        // mPayDetail.getNotifyUrl(),
        // password == null ? "" : RC4.encry_RC4_string(password,
        // MPConstants.KEY));


        String url = mPayDetail.getNotifyUrl().replace("payPassword=%s",
                "payPassword=");
        // params.put("result", result + "");
        url += "&result=" + result;
        CWLog.i("debug", "virtualPay:" + url);
        HttpRequest request = new HttpRequest(Request.Method.POST, url,
                new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError arg0) {
                        showError("网络异常，请稍后再试！");
                        isPayFailure = true;
                        getVirtualBalance(false);
                        hideProgress();
                    }
                }, new HttpRequest.ResponseCallback() {

            @Override
            public void success(Object obj, int resultCode,
                                int errorCode, String msg) {
                if (resultCode == 0 && errorCode == 0) {
                    PayResult pr = (PayResult) obj;
                    Intent intent = getIntent();
                    intent.setClass(EMainActivity.this,
                            PayStatusActivity.class);
                    intent.putExtra(PAY_RESULT, pr.getResult());
                    intent.putExtra(PAY_DETAIL, mPayDetail);
                    intent.putExtra(ADV_PKG_NAME, advPkgName);
                    startActivityForResult(intent, REQUEST_CODE);
                } else {
                    showError(resultCode, errorCode);
                    isPayFailure = true;
                    getVirtualBalance(false);
                }
                hideProgress();
            }

            @Override
            public void error(int errorCode, String msg) {
                showError(1, errorCode);
                isPayFailure = true;
                getVirtualBalance(false);
                hideProgress();
            }
        });
        request.setResponseDataType(HttpRequest.RESPONSE_DATA_TYPE_OBJECT);
        request.setResponseClazz(PayResult.class);
        Volley.newRequestQueue(getApplicationContext()).add(request);
    }


    /**
     * 习币支付
     */
    private void NewvirtualPay(final int result, String buyMsg, String userId, String userName) {
        // Map<String, String> params = new HashMap<String, String>();
        // String url = String.format(
        // mPayDetail.getNotifyUrl(),
        // password == null ? "" : RC4.encry_RC4_string(password,
        // MPConstants.KEY));


        Map<String, String> params = new HashMap<String, String>();
        params.put(HttpRequest.REQUEST_ACTION, MPAction.BUY_SERVICE_XIBI);
        params.put(HttpRequest.REQUEST_MODULES, getClass().getName());
        params.put("userId", userId);
        params.put("userName", userName);
        params.put("payPassword", "");
        params.put("buyMsg", buyMsg);
       
        
       /* String url = mPayDetail.getNotifyUrl().replace("payPassword=%s",
                "payPassword=");
        // params.put("result", result + "");
        url += "&result=" + result;
        CWLog.i("debug", "virtualPay:" + url);*/
        HttpRequest request = new HttpRequest(Request.Method.POST, params,
                new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError arg0) {
                        showError("网络异常，请稍后再试！");
                        isPayFailure = true;
                        getVirtualBalance(false);
                        hideProgress();
                    }
                }, new HttpRequest.ResponseCallback() {

            @Override
            public void success(Object obj, int resultCode,
                                int errorCode, String msg) {
                if (resultCode == 0 && errorCode == 0) {
                    PayResult pr = (PayResult) obj;
                    Intent intent = getIntent();
                    intent.setClass(EMainActivity.this,
                            PayStatusActivity.class);
                    intent.putExtra(PAY_RESULT, pr.getResult());
                    intent.putExtra(PAY_DETAIL, mPayDetail);
                    intent.putExtra(ADV_PKG_NAME, advPkgName);
                    startActivityForResult(intent, REQUEST_CODE);
                } else {
                    showError(resultCode, errorCode);
                    isPayFailure = true;
                    getVirtualBalance(false);
                }
                hideProgress();
            }

            @Override
            public void error(int errorCode, String msg) {
                showError(1, errorCode);
                isPayFailure = true;
                getVirtualBalance(false);
                hideProgress();
            }
        });
        request.setResponseDataType(HttpRequest.RESPONSE_DATA_TYPE_OBJECT);
        request.setResponseClazz(PayResult.class);
        Volley.newRequestQueue(getApplicationContext()).add(request);
    }

    private void showError(int ret, int errcode) {
        if (ret != 0) {
            switch (errcode) {
                case 101:
                    showError("服务禁用");
                    break;
                case 102:
                    showError("内部服务出错");
                    break;
                case 201:
                    showError("参数类型不正确");
                    break;
                case 202:
                    showError("缺少必选参数");
                    break;
                case 203:
                    showError("支付金额超出限制");
                    break;
                case 204:
                    showError("用户金额不足");
                    break;
                case 205:
                    showError("支付异常");
                    break;
                case 206:
                    showError("请设置支付密码");
                    break;
                case 301:
                    showError("无访问该接口权限");
                    break;
                case 4000:
                    showError("消息已被处理");
                    break;
                default:
                    showError("支付失败，请稍后尝试");
                    break;
            }
        }
    }

    /**
     * 创建支付情况Dialog
     */
    private void createPayDialog() {
        if (payDialog == null) {
            payDialog = new CWDialog(this);
            payDialog.setTitle("网上支付提示");
            payDialog.setTitleTextColor(Color.BLACK);
            payDialog.setMessage("\n支付完成后,请根据你的支付情况点击按钮!\n");
            payDialog.setPositiveButton("遇到问题", new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    payDialog.dismiss();
                }
            });
            payDialog.setNegativeButton("支付完成", new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // Intent intent = new Intent(MainActivity.this,
                    // PayStatusActivity.class);
                    // intent.putExtra(PAY_RESULT, success);
                    // intent.putExtra(PAY_DETAIL, mPayDetail);
                    // startActivityForResult(intent, REQUEST_CODE);
                    payDialog.dismiss();
                }
            });
        }
        payDialog.show();
    }

    /**
     * 开始支付
     */
    private void pay() {
        // mPayDetail.setNotifyUrl(mPayDetail.getNotifyUrl().replaceAll(
        // "%s",
        // RC4.encry_RC4_string(payMethodPasswordET.getText().toString(),
        // MPConstants.KEY)));
        mPayDetail.setNotifyUrl(mPayDetail.getNotifyUrl().replaceAll(
                "payPassword=%s", "payPassword="));
        if (payMethodVirtual.isChecked() && total <= vb.getAmount()) {
            // virtualPay(PAY_RESULT_SUCCES);
            //习币购买接口  //习币购买   类型为0   习币支付TYPE=4 
            getSignServerOrder(4, "0");

        } else {


            PayMethod payMethod = pmAdapter.getPayMethod();
            //当是在线报名的时  习币 余额为 0
            //busmsg是H5直接传过来
            if (2 == mPayDetail.getBuyType()) {
                //不需要落单   直接支付
                //获取订单流水号
                try {
                    String buymsg = mPayDetail.getBuymsg();
                    if ("".equals(buymsg) || null == buymsg) {
                        return;
                    }
                    //这里要判断一下是否安装微信
                    if (payMethod.getPayType() == PayMethod.PayType.PAY_TYPE_WEI_XIN) {

                        try {
                            ActivityInfo activityInfo = this.getPackageManager()
                                    .getActivityInfo(getComponentName(),
                                            PackageManager.GET_META_DATA);
                            String appId = activityInfo.metaData
                                    .getString("Weixin_PAY_APP_ID");
                            CWLog.e("debug", "appId : " + appId);
                            WxPayHelper.getInstance()
                                    .initPay(this, listener, appId);
                        } catch (NameNotFoundException e) {
                            e.printStackTrace();
                        }
//                        if (!WxPayHelper.getInstance().isWXAppInstalled()) {
//
//                            hideProgress();
//                            showError("您没有安装微信！");
//                            return;
//                        }

                    }


                    getUnifiedOrder(payMethod.getPayType(), buymsg);

                } catch (Exception e) {
                    e.getStackTrace();
                }

            } else {

                switch (payMethod.getPayType()) {
                    case PayMethod.PayType.PAY_TYPE_DETAIL:
                        showError("余额不足,请选择其它支付方式!");
                        hideProgress();
                        break;
                    case PayMethod.PayType.PAY_TYPE_WEI_XIN:
                        try {
                            ActivityInfo activityInfo = this.getPackageManager()
                                    .getActivityInfo(getComponentName(),
                                            PackageManager.GET_META_DATA);
                            String appId = activityInfo.metaData
                                    .getString("Weixin_PAY_APP_ID");
                            CWLog.i("debug", "appId : " + appId);
                            WxPayHelper.getInstance()
                                    .initPay(this, listener, appId);
                        } catch (NameNotFoundException e) {
                            e.printStackTrace();
                        }
//                        if (WxPayHelper.getInstance().isWXAppInstalled()) {
                        //getUnifiedOrder(payMethod.getPayType());
                        //获取签名//20微信支付
                        getSignServerOrder(payMethod.getPayType(), "20");
//                        } else {
//                            hideProgress();
//                                      showError("您没有安装微信！");
//                            Intent qrPayIntent = new Intent(this, QRCodePayActivity.class);
//                            startActivity(qrPayIntent);
//                        }
                        break;
                    case PayMethod.PayType.PAY_TYPE_ALIPAY:
                        getSignServerOrder(payMethod.getPayType(), "1");//1：支付宝
                        break;
                    default:
                        showError("功能模块研发中...");
                        break;
                }
            }


        }
    }

    /**
     * 验证习币支付密码
     */
    private void passwordVerify() {
        if (vb.isPaypwd()
                && "".equals(payMethodPasswordET.getText().toString())) {
            showError("请输入支付密码");
            hideProgress();
            return;
        }
        Map<String, String> params = new HashMap<String, String>();
        params.put(HttpRequest.REQUEST_ACTION, MPAction.PASSWORD_VERIFY);
        params.put(HttpRequest.REQUEST_MODULES, getClass().getName());
        params.put("userId", mPayDetail.getUserId() + "");//
        String password = RC4.encry_RC4_string(payMethodPasswordET.getText()
                .toString(), MPConstants.KEY);
        params.put("password", password);
        HttpRequest request = new HttpRequest(params,
                new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError arg0) {
                        showError("支付失败，请稍后尝试");
                        hideProgress();
                    }
                }, new HttpRequest.ResponseCallback() {

            @Override
            public void success(Object obj, int resultCode,
                                int errorCode, String msg) {
                boolean success = (Boolean) obj;
                if (resultCode == 0 && success) {
                    pay();
                } else {
                    CWLog.e("debug", "resultCode:" + resultCode
                            + "    msg:" + msg + "      success:"
                            + success);
                    if (!success) {
                        showError("支付密码错误");
                    } else {
                        showError("支付失败，请稍后尝试");
                    }
                    hideProgress();
                }
            }

            @Override
            public void error(int errorCode, String msg) {
                showError("支付失败，请稍后尝试");
                hideProgress();
            }
        });
        request.setResponseDataType(HttpRequest.RESPONSE_DATA_TYPE_OBJECT);
        request.setResponseClazz(Boolean.class);
        Volley.newRequestQueue(getApplicationContext()).add(request);
    }

    /**
     * 拷贝asset目录下文件到sd卡上
     *
     * @param srcfilename 文件名
     * @param file        文件路径
     * @return 复制文件
     */
    public boolean copyFile(String srcfilename, File file) {
        FileOutputStream fos = null;
        try {
            final int bufferSize = 1024;
            AssetManager am = getResources().getAssets();
            InputStream is = am.open(srcfilename);
            fos = new FileOutputStream(file);
            byte[] buffer = new byte[bufferSize];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            fos.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 查询银联支付结果
     */
    private void unionPayQuery() {
        showProgress("正在验证支付状态");
        Map<String, String> params = new HashMap<String, String>();
        params.put(HttpRequest.REQUEST_ACTION, MPAction.UNION_PAY_QUERY);
        params.put(HttpRequest.REQUEST_MODULES, getClass().getName());
        params.put("orderNum", order.getRechargeNo());
        params.put("orderTime", orderTime);
        HttpRequest request = new HttpRequest(params,
                new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError arg0) {
                        showError("网络异常，请稍后再试！");
                        isPayFailure = true;
                        getVirtualBalance(false);
                        hideProgress();
                    }
                }, new HttpRequest.ResponseCallback() {

            @Override
            public void success(Object obj, int resultCode,
                                int errorCode, String msg) {
                if (resultCode == 0 && errorCode == 0) {
                    UnionPayResult upr = (UnionPayResult) obj;
                    int payResult;
                    CWLog.e("debug", "isResult:" + upr.isResult());
                    if (upr.isResult() && success) {
                        payResult = PAY_RESULT_SUCCES;
                    } else {
                        if (success) {
                            payResult = PAY_RESULT_DELAY;
                        } else {
                            payResult = PAY_RESULT_FAIL;
                        }
                    }
                    virtualPay(payResult);
                } else {
                    isPayFailure = true;
                    getVirtualBalance(false);
                    showError(msg);
                    hideProgress();
                }
            }

            @Override
            public void error(int errorCode, String msg) {
                showError(String.valueOf(msg));
                isPayFailure = true;
                getVirtualBalance(false);
                hideProgress();
            }
        });
        request.setResponseDataType(HttpRequest.RESPONSE_DATA_TYPE_OBJECT);
        request.setResponseClazz(UnionPayResult.class);
        Volley.newRequestQueue(getApplicationContext()).add(request);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        CWLog.i("debug", "onClick");
        if (id == EPayMethodContainer.balanceContainer) {
            getVirtualBalance(true);
        }
    }

    // -----------------------------支付宝支付相关--------------------------->
    /**
     * 待签名的订单
     */
    private String orderInfoStr = "";

    /**
     * 订单签名结果
     */
    private String signStr = "";

    /**
     * 支付宝支付结果回调
     */
    private AlipayResultCallBack mAliPayCallBack = new AlipayResultCallBack();

    /**
     * AliPay助手
     */
    private AlipayHelper alipayHelper = new AlipayHelper(this, mAliPayCallBack);

    /**
     * Alipay支付结果回调
     */
    private class AlipayResultCallBack implements AlipayListener {

        @Override
        public void onAliPaySucc(String resultInfo) {
            CWLog.d("PayRequest", "onAliPaySucc:结果:" + resultInfo);
            success = true;
            getRechargeInfo(mPayDetail.getUserId(), order.getRechargeNo());
            // String sign = getSignStr(resultInfo);
            // verifyAlipayMobileSign(orderInfoStr, sign);
        }

        @Override
        public void onAliPaying(String msg) {
            showSuccess(msg);
        }

        @Override
        public void onAliPayFailure(String msg) {
            success = false;
            showError(msg);
        }

        @Override
        public void onAliPayErr(int errCode, String errMsg) {
            success = false;
            showError(errCode + "_" + errMsg);
        }
    }

    /**
     * 从支付宝成功结果中获取签名(用于公钥做验签)
     *
     * @param result
     * @return
     */
    private String getSignStr(String result) {
        String sign = "";
        String[] resultParams = result.split("&");
        for (String resultParam : resultParams) {
            if (resultParam.startsWith("sign=")) {
                sign = resultParam.substring(6, resultParam.length() - 1);
            }
        }
        return sign;
    }

    /**
     * 取得要支付的最终金额
     *
     * @return
     */
    private double getPayMoney() {
        return total - (payMethodVirtual.isChecked() ? vb.getAmount() : 0);
    }


    public void getSignServerOrder(final int payType, final String rechargeType) {
        final SignParms signparms = mPayDetail.getSingParms();
        if (signparms == null) {
            CWLog.d("debug", "getSignServerOrder签名参数为空:"
            );
            hideProgress();
            return;
        }

        Map<String, String> params = new HashMap<String, String>();
        if (mPayDetail.getKeyCode() == null) {
            params.put(HttpRequest.REQUEST_ACTION, MPAction.SET_EPAGE_SERVICE_ORDER);
            params.put(HttpRequest.REQUEST_MODULES, getClass().getName());
        } else {
            params.put(HttpRequest.REQUEST_ACTION, MPAction.SET_EPAGE_SERVICE_ORDER_BY_COUPON);
            params.put(HttpRequest.REQUEST_MODULES, getClass().getName());
            params.put("total_price", mPayDetail.getPrice() + "");
            params.put("keyCode", mPayDetail.getKeyCode() + "");
            params.put("sub_fee", mPayDetail.getAmount() + "");
        }
        params.put("brandId", signparms.getBrandId() + "");
        params.put("serviceId", signparms.getServiceId());
        params.put("userId", signparms.getUserId() + "");
        params.put("userName", signparms.getUserName());
        params.put("total_fee", PayUtil.radixPoint(signparms.getTotal_fee(), 2));
        params.put("goods_num", signparms.getGoods_num() + "");
        params.put("rechargeType", rechargeType);

        HttpRequest request = new HttpRequest(params,
                new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError arg0) {
                        CWLog.d("debug", arg0.toString() + "getSignServerOrder获取订单签名出错 onErrorResponse!");
                        hideProgress();
                    }
                }, new HttpRequest.ResponseCallback() {

            @Override
            public void success(Object obj, int resultCode,
                                int errorCode, String msg) {
                CWLog.e("debug", String.valueOf(obj));
                if (resultCode == 0 && errorCode == 0) {

                    SignResult signresult = (SignResult) obj;
                    if (signresult.isFlag()) {
                        if (null != signresult.getBugmsg() && !"".equals(signresult.getBugmsg())) {
                            if (payType == 4) {
                                try {

                                    //获取签名后   习币购买
                                    NewvirtualPay(PAY_RESULT_SUCCES, URLEncoder.encode(signresult.getBugmsg(), "utf-8"), signparms.getUserId() + "", signparms.getUserName());
                                } catch (Exception e) {
                                    e.getStackTrace();
                                }


                            } else {
                                //获取订单流水号
                                getUnifiedOrder(payType, signresult.getBugmsg());
                                CWLog.d("debug", "getSignServerOrder成功结果:bugmsg:="
                                        + signresult.getBugmsg());
                            }


                        } else if ("".equals(signresult.getBugmsg())) {

                            CWLog.i("debug", "getSignServerOrder成功结果:msg:=" +
                                    "0元购买 ");
                            //0元购买   直接返回
                            Intent intent = new Intent();
                            intent.putExtra(EMainActivity.PAY_RESULT, PAY_RESULT_SUCCES);
                            setResult(RESULT_OK);
                            finish();

                        }

                    } else {

                        CWLog.d("debug", "getSignServerOrder获取签名失败 "
                        );
                    }


                } else {
                    CWLog.d("debug", "getSignServerOrder获取签名失败 "
                    );
                }
                hideProgress();
            }


            @Override
            public void error(int errorCode, String msg) {
                CWLog.d("debug", "getSignServerOrder获取签名失败 error:"
                        + errorCode + "msg=" + msg);
                hideProgress();
            }
        });


        request.setResponseDataType(HttpRequest.RESPONSE_DATA_TYPE_OBJECT);
        request.setResponseClazz(SignResult.class);
        Volley.newRequestQueue(getApplicationContext()).add(request);


    }


    /**
     * 获取订单流水号
     * /v2/pay/PayRecharge/PurchaseUserPayInRecord
     * http://exapi.ciwong.com/v2/pay/EpapePay/Bealone
     * 修改为
     * 请求方式变成POST
     *
     * @param payType 支付类型
     */
    public void getUnifiedOrder(final int payType, final String buyMsg) {

        //String url;
        List<String> add = new ArrayList<String>();
        Map<String, String> params = new HashMap<String, String>();
        params.put(HttpRequest.REQUEST_ACTION, MPAction.GET_UNIFIED_ORDER);
        params.put(HttpRequest.REQUEST_MODULES, getClass().getName());
        //add.add("_input_charset=utf-8");

        String money = PayUtil.radixPoint(getPayMoney(), 2);
        params.put("rechargeAmount", "" + money);
        // add.add("rechargeAmount=" + money);
        params.put("typeId", mPayDetail.getTypeId() + "");
        int rechargeType;
        switch (payType) {
            case PayMethod.PayType.PAY_TYPE_ALIPAY:
                rechargeType = 1;
                BaseApplication eApplication = BaseApplication.getInstance();
                String packageName = "";
                if (eApplication != null) {
                    packageName = eApplication.getPackageName();
                }
                if ("com.ciwong.listenspeak".equals(packageName)) {
                    params.put("typeId", 3 + "");
                } else {
                    params.put("typeId", mPayDetail.getTypeId() + "");
                }
                break;
            default:
                rechargeType = 20;
                break;
        }
        params.put("rechargeType", rechargeType + "");
        //add.add("rechargeType=" + rechargeType);
        params.put("userId", "" + mPayDetail.getUserId());

        //传入的时候已经编过遍码了
        params.put("userName", mPayDetail.getUsername());

        //add.add("userId=" + mPayDetail.getUserId());
//        try
//        {
//            params.put("userName",URLEncoder.encode(mPayDetail.getUsername(), "utf-8"));
//        }
//        catch (UnsupportedEncodingException e)
//        {
//            e.printStackTrace();
//        }

        params.put("ip", "" + mPayDetail.getVerifyInfo().getClientIp());
        //1  直接购买 默认传1   0 不直接购买
        params.put("isBuy", mPayDetail.getIsBuy() + "");
        //String buyMsg = concatBuyMsg(add);
        //params.put("buyMsg", URLEncoder.encode(buyMsg));
        params.put("buyMsg", URLEncoder.encode(buyMsg));
        //url=HttpHelper.concatUrl(params, MPAction.GET_UNIFIED_ORDER
        //       + HttpHelper.getVerifyStr(HttpRequest.getVerifyInfo()));
        //如果没有安装微信 或者是hd 版本，增加以下两个参数，获取二维码。
        if (!WxPayHelper.getInstance().isWXAppInstalled() || BaseApplication.PLATFORM_ENV == BaseApplication.PLATFORM_PAD) {
            String body = mPayDetail.getName() + "(" + mPayDetail.getSingParms().getGoods_num() + "个月)";
            params.put("trade_type", "NATIVE");
            params.put("body", body);
            params.put("product_id", mPayDetail.getSingParms().getServiceId());
        }
        //改为  POST请求
        HttpRequest request = new HttpRequest(Request.Method.POST, params,
                new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError arg0) {
                        switch (payType) {
                            case PayMethod.PayType.PAY_TYPE_ALIPAY:
                                mAliPayCallBack.onAliPayFailure("获取订单流水号出错!");
                                CWLog.d("debug", arg0.toString() + "PAY_TYPE_ALIPAY获取订单流水号出错!");
                                break;
                            default:
                                listener.onWXPayFailure(-1, "获取订单流水号出错!");
                                CWLog.d("debug", arg0.toString() + "onWXPayFailure获取订单流水号出错!");
                                break;


                        }
                        hideProgress();
                    }
                }, new HttpRequest.ResponseCallback() {

            @Override
            public void success(Object obj, int resultCode,
                                int errorCode, String msg) {

//                CWLog.e("debug", String.valueOf(obj));
                CWLog.d("debug", "#####下单成功###");
                CWLog.d("debug", String.valueOf(obj));
                if (resultCode == 0 && errorCode == 0) {
                    order = (OrderInfo) obj;
                    switch (payType) {
                        case PayMethod.PayType.PAY_TYPE_ALIPAY:
                            getAlipayMobileSign();// 跳转到支付宝支付
                            break;
                        default:
                            if (payType == PayMethod.PayType.PAY_TYPE_WEI_XIN && !TextUtils.isEmpty(order.code_url)) {//微信支付的扫码支付
                                Intent qrPayIntent = new Intent(EMainActivity.this, QRCodePayActivity.class);
                                qrPayIntent.putExtra("code_url", order.code_url);
                                startActivityForResult(qrPayIntent, REQUEST_CODE_QRCODE_PAY);
                            } else {//跳转微信支付
                                WxPayHelper.getInstance().sendReq(order);
                            }
                            break;
                    }
                } else {
                    switch (payType) {
                        case PayMethod.PayType.PAY_TYPE_ALIPAY:
                            mAliPayCallBack
                                    .onAliPayFailure("获取订单流水号出错!");
                            break;
                        default:
                            listener.onWXPayFailure(-1, "获取订单流水号出错!");
                            break;
                    }
                }
                hideProgress();
            }

            @Override
            public void error(int errorCode, String msg) {
                switch (payType) {
                    case PayMethod.PayType.PAY_TYPE_ALIPAY:
                        mAliPayCallBack.onAliPayFailure("获取订单流水号出错!");
                        break;

                    default:
                        listener.onWXPayFailure(errorCode, msg);
                        break;
                }
                hideProgress();
            }


        });
        //request.setContentType("Content-Type", "application/json");
        request.setResponseDataType(HttpRequest.RESPONSE_DATA_TYPE_OBJECT);
        request.setResponseClazz(OrderInfo.class);

        Volley.newRequestQueue(getApplicationContext()).add(request);
    }

    /**
     * 获取支付宝支付签名(成功后，请求支付宝支付)
     */
    public void getAlipayMobileSign() {
        String price = PayUtil.radixPoint(getPayMoney(), 2);
        orderInfoStr = alipayHelper.getOrderInfo(order, mPayDetail, price);
        Map<String, String> params = new HashMap<String, String>();
        params.put(HttpRequest.REQUEST_ACTION, MPAction.GET_ALIPAY_MOBILE_SIGN);
        params.put(HttpRequest.REQUEST_MODULES, getClass().getName());
        params.put("content", URLEncoder.encode(orderInfoStr));
        params.put("input_charset", "UTF-8");
        BaseApplication eApplication = BaseApplication.getInstance();
        String packageName = "";
        if (eApplication != null) {
            packageName = eApplication.getPackageName();
        }
        if ("com.ciwong.listenspeak".equals(packageName)) {
            params.put("typeId", 3 + "");
        } else {
            params.put("typeId", mPayDetail.getTypeId() + "");
        }
        HttpRequest request = new HttpRequest(params,
                new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError arg0) {
                        mAliPayCallBack.onAliPayFailure("获取支付宝支付签名出错!");
                        hideProgress();
                    }
                }, new HttpRequest.ResponseCallback() {

            @Override
            public void success(String responseStr) {
                CWLog.d("PayRequest", "getAlipayMobileSign成功结果:"
                        + responseStr);
                try {
                    JSONObject json = new JSONObject(responseStr);
                    if (json.has("errcode") && json.has("ret")) {
                        final int res = json.getInt("ret");
                        final int errorCode = json.getInt("errcode");
                        if (res == 0 && errorCode == 0
                                && json.has("data")) {
                            JSONObject data = new JSONObject(json
                                    .getString("data"));
                            if (data.has("sign")) {
                                signStr = data.getString("sign");
                                if (signStr != null
                                        && !signStr.equals("")) {
                                    alipayHelper.payAction(
                                            orderInfoStr, signStr);
                                } else {
                                    mAliPayCallBack
                                            .onAliPayFailure("获取支付宝支付签名出错!");
                                }
                            } else {
                                mAliPayCallBack
                                        .onAliPayFailure("获取支付宝支付签名出错!");
                            }
                        } else {
                            mAliPayCallBack
                                    .onAliPayFailure("获取支付宝支付签名出错!");
                        }
                    } else {
                        mAliPayCallBack.onAliPayFailure("获取支付宝支付签名出错!");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    mAliPayCallBack.onAliPayFailure("获取支付宝支付签名出错!");
                }
                hideProgress();
            }

            @Override
            public void error(int errorCode, String msg) {
                mAliPayCallBack.onAliPayFailure("获取支付宝支付签名出错!");
                hideProgress();
            }
        });
        Volley.newRequestQueue(getApplicationContext()).add(request);
    }

    /**
     * 根用户编码获取冲值记录(请求成功后，调用习币进行支付)
     *
     * @param userId
     * @param rechargeNo
     */
    private void getRechargeInfo(final long userId, final String rechargeNo) {
        showProgress("正在查询订单");
        Map<String, String> params = new HashMap<String, String>();
        params.put(HttpRequest.REQUEST_ACTION, MPAction.GET_GET_RECHARGE_INFO);
        params.put(HttpRequest.REQUEST_MODULES, getClass().getName());
        params.put("userId", "" + userId);
        params.put("rechargeNo", rechargeNo);

        HttpRequest request = new HttpRequest(params,
                new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError arg0) {
                        showError("网络异常，请稍后再试！");
                        isPayFailure = true;
                        getVirtualBalance(false);
                        hideProgress();
                    }
                }, new HttpRequest.ResponseCallback() {

            @Override
            public void success(Object obj, int resultCode,
                                int errorCode, String msg) {
                CWLog.e("debug", String.valueOf(obj));
                if (resultCode == 0 && errorCode == 0) {
                    count++;
                    Recharge recharge = (Recharge) obj;
                    int payResult = 0;
                    if (recharge.getStatus() == 1 && success) {
                        payResult = PAY_RESULT_SUCCES;
                    } else {
                        if (recharge.getStatus() == 0 && count < 3) {
                            mHandler.postDelayed(new Runnable() {

                                @Override
                                public void run() {
                                    getRechargeInfo(userId, rechargeNo);
                                }
                            }, 5000);
                            return;
                        } else {
                            payResult = PAY_RESULT_FAIL;
                        }
                    }
                    payJump(payResult);
                } else {
                    isPayFailure = true;
                    getVirtualBalance(false);
                    showError(msg);
                    hideProgress();
                }
            }

            @Override
            public void error(int errorCode, String msg) {
                showError(String.valueOf(msg));
                isPayFailure = true;
                getVirtualBalance(false);
                hideProgress();
            }
        });
        request.setResponseClazz(Recharge.class);
        request.setResponseDataType(HttpRequest.RESPONSE_DATA_TYPE_OBJECT);
        Volley.newRequestQueue(getApplicationContext()).add(request);
    }

    private String concatBuyMsg(List<String> add) {
        List<String> buyMsgs = mPayDetail.getBuyMsgs();
        add.addAll(0, buyMsgs);
        int size = add.size();
        String[] array = add.toArray(new String[size]);
        StringBuilder builder = new StringBuilder();
        int index = 0;
        for (String s : array) {
            if (index != 0) {
                builder.append("&");
            }
            builder.append(s);
            index++;
        }
        builder.append("17a4dgbcx3d58dca44788rtwc47cghfhd3csd8a6e29c31asd");
        CWLog.d("debug", builder.toString() + "支付签名之前");

        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            CWLog.d("debug", builder.toString() + "支付签名");
            messageDigest.update(builder.toString().getBytes());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
        String hexString = toHexString(messageDigest.digest());
        builder.setLength(0);
        for (String s : buyMsgs) {
            builder.append(s);
            builder.append("&");
        }
        builder.append("sign=");
        builder.append(hexString);
        builder.append("&");
        builder.append("sign_type=");
        builder.append("md5");

        CWLog.d("debug", builder.toString() + "支付签名  最终");
        return builder.toString();
    }

    /**
     * 以十六进制（基数 16）无符号整数形式返回一个整数参数的字符串表示形式
     *
     * @param bytes 字节数组
     * @return 参数的十六进制（基数 16）无符号整数值的字符串表示形式
     */
    private String toHexString(byte[] bytes) {
        StringBuilder builder = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xFF & b);
            if (hex.length() == 1) {
                builder.append("0");
            }
            builder.append(hex);
        }
        CWLog.d("debug", builder.toString());
        return builder.toString();
    }

    /**
     * 验签名(成功后，进行支付操作)
     *
     * @param content
     * @param sign
     */
    // private void verifyAlipayMobileSign(final String content, final String
    // sign)
    // {
    // CWLog.d("PayRequest", "verifyAlipayMobileSign:" + "_content:" + content
    // + "_sign:" + sign);
    // Map<String, String> params = new HashMap<String, String>();
    // params.put(AsyncLoadData.REQUEST_ACTION,
    // MPAction.GET_VERIFY_ALIPAY_MOBILE_SIGN);
    // params.put("content", URLEncoder.encode(content));
    // params.put("sign", sign);
    // params.put("input_charset", "UTF-8");
    // AsyncLoadData request = new AsyncLoadData(this, params,
    // new AsyncLoadData.RequestCallback()
    // {
    //
    // @Override
    // public void success(int resultCode, String msg)
    // {
    // CWLog.d("PayRequest", "verifyAlipayMobileSign:成功" + msg);
    // if (resultCode == 0)
    // {
    // success = true;
    // isUnionPay = true;
    // // getVirtualBalance(true);
    // getVirtualBalance(true);
    // showSuccess("支付真正的成功!");
    // }
    // else
    // {
    // getVirtualBalance(true);
    // }
    // hideProgress();
    // }
    //
    // @Override
    // public void error(int errorType)
    // {
    // CWLog.d("PayRequest", "verifyAlipayMobileSign:失败"
    // + errorType);
    // hideProgress();
    // }
    // }, null, new OnClickViewLoadDataListener()
    // {
    // @Override
    // public void reload()
    // {
    // verifyAlipayMobileSign(content, sign);
    // }
    // });
    // request.setResultType(AsyncLoadData.RESULT_DATA_TYPE_STRING);
    // request.disableProgressDialog();
    // request.disableToast();
    // request.execute();
    // }
}
